package be.pluyckx.batteryprogress.activity.fragment.info.history;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTabHost;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

import be.pluyckx.batteryprogress.R;
import be.pluyckx.batteryprogress.application.Constants;
import be.pluyckx.batteryprogress.data.history.BatteryHistory;

/**
 * Created by Philip on 21/08/13.
 * <p>
 * A Fragment that holds a TabHost to switch between different views for the BatteryHistory.
 */
public class HistoryFragment extends Fragment {
  private static String KEY_LAST_TAB = "history_last_tab";

  private FragmentTabHost mTabHostHistory;
  private BatteryHistory mBatteryHistory = BatteryHistory.getHistory();
  private Button bClearHistory;
  private Button bClearAllHistory;

  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.fragment_history, container, false);

    bClearHistory = (Button) v.findViewById(R.id.b_clear_history);
    bClearHistory.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View view) {
        mBatteryHistory.clear();
      }
    });
    bClearAllHistory = (Button) v.findViewById(R.id.b_clear_history_all);
    bClearAllHistory.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View view) {
        mBatteryHistory.clear(true);
      }
    });

    mTabHostHistory = (FragmentTabHost) v.findViewById(R.id.tabhost_history);
    mTabHostHistory.setup(getActivity(), getActivity().getSupportFragmentManager(), R.id.realtabcontent_history);

    initTabs();

    return v;
  }

  /**
   * Initialize the tabs
   */
  private void initTabs() {
    String tabTitle = getResources().getString(R.string.tab_list_history);
    mTabHostHistory.addTab(mTabHostHistory.newTabSpec(tabTitle).setIndicator(tabTitle),
        ListHistoryFragment.class, null);

    tabTitle = getResources().getString(R.string.tab_graph_history);
    mTabHostHistory.addTab(mTabHostHistory.newTabSpec(tabTitle).setIndicator(tabTitle),
        ChartFragment.class, null);
  }

  @Override
  public void onResume() {
    super.onResume();

    mTabHostHistory.setCurrentTab(getActivity().getSharedPreferences(Constants.PREFERENCES_NAME,
        Context.MODE_PRIVATE).getInt(KEY_LAST_TAB,
        0));
  }

  @Override
  public void onPause() {

    getActivity().getSharedPreferences(Constants.PREFERENCES_NAME, Context.MODE_PRIVATE)
        .edit()
        .putInt(KEY_LAST_TAB, mTabHostHistory.getCurrentTab())
        .commit();

    super.onPause();
  }
}
